package tree

type Node struct {
	Val   int
	Left  *Node
	Right *Node
}

//2
///\
//3 4
///\ /\
//5 67 8
// NetTestNode 创建示例的TreeNode
func GetTestNode() *Node {
	root := &Node{Val: 2}

	root5 := &Node{Val: 5}
	root6 := &Node{Val: 6}
	root7 := &Node{Val: 7}
	root8 := &Node{Val: 8}

	root3 := &Node{Val: 3}
	root3.Left = root5
	root3.Right = root6

	root4 := &Node{Val: 4}
	root4.Left = root7
	root4.Right = root8

	root.Left = root3
	root.Right = root4

	return root

}

func GetNodeByVal(val int) *Node {
	root := GetTestNode()
	return getTreeNodeByVal(root, val)
}

func getTreeNodeByVal(root *Node, val int) *Node {

	if root == nil {
		return root
	}

	if root.Val == val {
		return root
	}

	left := getTreeNodeByVal(root.Left, val)
	right := getTreeNodeByVal(root.Right, val)

	if left != nil && left.Val == val {
		return left
	}
	if right != nil && right.Val == val {
		return right
	}
	return nil
}
